package ru.spbau.database.group3.queryEvaluator;

import ru.spbau.database.group3.engine.DatabaseEngine;
import ru.spbau.database.group3.generator.InsertQueryGenerator;
import ru.spbau.database.group3.parser.Parser;

import java.io.*;

/**
 * @author: stas
 * @date: 2/6/13
 * @time: 1:23 PM
 */
public class QueryEvaluator {
    private final Parser parser;
    private final DatabaseEngine databaseEngine;

    public QueryEvaluator(String path) throws ClassNotFoundException, IOException {
        this.parser = new Parser();
        this.databaseEngine = DatabaseEngine.getInstance(path);
    }

    public void start() throws IOException, ClassNotFoundException {
        String query;
        String result;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            query = br.readLine();
            if(query.equals("EXIT")) {
                stop();
                System.out.println("Bye!");
                break;
            }
            if(query.matches("INSERT [0-9]+")) {
                long time = System.currentTimeMillis();
                insertRandomRecords(query);
                System.out.println("time: " + (System.currentTimeMillis() - time));
                continue;
            }
            result = evaluateQuery(query);
            System.out.println(result);
        }
        br.close();
    }

    private void insertRandomRecords(String query) throws ClassNotFoundException, IOException {
        int n = Integer.valueOf(query.substring(query.indexOf(" ")).trim());
        for(int i = 0; i < n; ++i) {
            String insertQuery = InsertQueryGenerator.getNextInsertQuery();
            //System.out.println(insertQuery);
            evaluateQuery(insertQuery);
//            System.out.println(evaluateQuery(insertQuery) + "  " +  i);
        }
        System.out.println(new OKResult().getStringResult() + "  " +  n);
    }


    private String evaluateQuery(String query) throws IOException, ClassNotFoundException {
        try {
            Instruction instruction = parser.parse(query);
            QueryResult queryResult = instruction.handle(databaseEngine);
            return queryResult.getStringResult();
        } catch (IOException e) {
            return new ErrorResult(e.getMessage()).getStringResult();
        } catch (ClassNotFoundException e) {
            return new ErrorResult(e.getMessage()).getStringResult();
        } catch (IllegalArgumentException e){
            return new ErrorResult(e.getMessage()).getStringResult();
        }
    }

    private void stop() throws IOException {
        databaseEngine.dump();
    }
}
